// pages/testImg/testImg.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    task_id: null,
    kmapping_id: null,
    paper_ids: '',
    code: '',
    curIndex: -1,//当前选择拍照的索引值
    firstEnter: true,//是否是刚进入-用于初始化加载数据-加载结束改为false
    isCallGetAiImg: false,//是否在调用getTestImg-避免重复调用
    isCallCheckPageStatusNew: false,//是否在调用图片验证
    isTakingPhoto: false,//是否正在拍照选图
    isWaitingForCheckStatus: false,//是否在进入等待验证图片
    isUploadingImg: false,//是否正在上传图片
    testInfo: [
      // {
      //   "paper_id": "3341",
      //   "page": "3页",
      //   "paper_img_url": "http://eagle.snslearn.com/md/2db209c59d8bcaced1c0897f8c798bf8",
      //   "status": 1,
      //   "old_paper_img_url":"http://eagle.snslearn.com/md/2db209c59d8bcaced1c0897f8c798bf8",
      //   "paper_status": 1
      // }
    ],
    codeInfo: {
      // app_id: '1101',
      // paper_download_task_id: '2096',
      // page: '1',
      // download_task_id: '264'
    },
    photoTip: {
      photoTip: false,
      indicatorDots: true,
      autoplay: false,
      interval: 3000,
      duration: 500,
      current: 0,
      tipArr: [{
          img_src: '/images/bz.jpg',
          tip_title: '拍题示范',
          tip_content_a: '光线充足,对焦清晰',
          tip_content_b: '黑色边框全部装入镜头'
        },
        {
          img_src: '/images/dsy.jpg',
          tip_title: '错误案例一:',
          tip_content_a: '有水印,可在手机设置中取消水印'
        },
        {
          img_src: '/images/bkbq.jpg',
          tip_title: '错误案例二:',
          tip_content_a: '边框不完整,尽可能镜头和答题纸保持平行保证边框完整'
        },
        {
          img_src: '/images/bz.jpg',
          dark: true,
          tip_title: '错误案例三:',
          tip_content_a: '光线很暗,保证周围光线充足'
        }
      ]
    }
  },

  /**
   * 点击试卷图片
   */
  tapImg: function(e) {
    var _this = this,
      _index = e.currentTarget.dataset.index,
      testImg = _this.data.testImg,
      testInfo = _this.data.testInfo,
      _download_task_id = _this.data.codeInfo.download_task_id;
    var imgUrl = testInfo[_index].old_paper_img_url;
    if (imgUrl) {
      wx.previewImage({
        current: imgUrl, // 当前显示图片的http链接
        urls: testImg // 需要预览的图片http链接列表
      })
    } else if (!imgUrl && testInfo[_index].paper_status != 1) {
      var photoNum = wx.getStorageSync('photoNum');
      if (photoNum) {
        wx.setStorageSync('photoNum', photoNum + 1);
        if (photoNum <= 3) {
          _this.setData({
            'photoTip.photoTip': true,
            'curIndex': _index
          })
        } else {
          _this.setData({
            'photoTip.photoTip': false,
            'photoTip.current': 0,
            'curIndex': _index
          });
          _this.takePhoto();
        }
      } else {
        wx.setStorageSync('photoNum', 1);
        _this.setData({
          'photoTip.photoTip': true,
          'curIndex': _index
        })
      }
    }
  },

  /**
   * 拍照提示跳出
   */
  skip: function() {
    var _this = this;
    _this.setData({
      'photoTip.photoTip': false,
      'photoTip.current': 0
    })
    _this.takePhoto();
  },

  swiperChange: function(event) {
    var _this = this;
    _this.setData({
      'photoTip.current': event.detail.current
    })
  },

  /**
   * 提示弹框滑到最后一页在滑动,跳出
   */
  transitionTip: function(event) {
    var _this = this,
      current = _this.data.photoTip.current;
    if (current == 3 && event.detail.dx > 10) {
      _this.setData({
        'photoTip.photoTip': false,
        'photoTip.current': 0
      })
      _this.takePhoto();
    }
  },

  /**
   * 调用原生相机拍照
   */
  takePhoto: function() {
    var _this = this,
      index = _this.data.curIndex;//index:所点击拍照位置的索引
    _this.setData({
      isTakingPhoto: true
    });
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        wx.showLoading({
          title: '上传中',
          mask: true
        })
        _this.setData({
          isTakingPhoto: false,
          isUploadingImg: true
        });
        wx.uploadFile({
          url: app.globalData.URL + '/index.php?app=interface&mod=Resource&act=upload&file_type=image&' + app.globalData.URLBOOL,
          method: 'POST',
          filePath: tempFilePaths[0],
          name: 'image',
          dataType: 'json',
          success(res) {
            var data = JSON.parse(res.data);
            
            if (data.error_code == 0) {
              var _data = data.data,
                _md = _data[0].md;
              _this.setData({
                isCallCheckPageStatusNew: true
              });
              wx.request({
                url: app.globalData.URL + '/kmapping/WebAppAjax/checkPageStatusNew?' + app.globalData.URLBOOL,
                method: 'GET',
                data: {
                  md: _md,
                  wechat_flag: 1,
                  download_task_id: _this.data.codeInfo.download_task_id,
                  paper_page: _this.data.testInfo[index].paper_page,
                  paper_id: _this.data.paper_id
                },
                success(_res) {
                  wx.hideLoading();
                  var res = _res.data;
                  if (res.error_code == 0) {
                    var _result = res.barcode;
                    _result = _result.split("&");
                    var app_id = _result[0],
                      paper_download_task_id = _result[1],
                      page = _result[2],
                      download_task_id = _result[3];
                    if (_result[0] != 1101) {
                      wx.showToast({
                        title: '该套试题未启用!',
                        icon: 'none',
                        mask: true,
                        duration: 2000
                      })
                      return false;
                    }
                    _this.imgPosition(paper_download_task_id, page, _md, download_task_id);
                  } else {
                    wx.showToast({
                      title: res.error_msg,
                      icon: 'none',
                      mask: true,
                      duration: 2000
                    })
                  }
                },
                complete: function(){
                  _this.setData({
                    isCallCheckPageStatusNew: false
                  })
                },
                fail(_res) {
                  wx.showToast({
                    title: _res.errMsg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }
          },
          complete: function(){
            _this.setData({
              isUploadingImg: false
            })
          }
        })
      },
      complete:function(){
        _this.setData({
          isTakingPhoto: false
        });
      }
    })
  },
  /**
   *确认图片位置 
   */
  imgPosition: function(paper_download_task_id, paper_page, md, download_task_id) {
    var _this = this,
      _testInfo = _this.data.testInfo,
      _download_task_id = _this.data.codeInfo.download_task_id;
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/userAnswerSplit?' + app.globalData.URLBOOL,
      method: 'GET',
      data: {
        //_testInfo[_index].
        user_paper_img_info: [{
          "task_id": paper_download_task_id,
          "page_info": [{
            //_testInfo[_index].
            "page": paper_page,
            "md": md
          }]
        }],
        kmapping_download_task_id: download_task_id,
        wechat_flag: 1
      },
      success(_res) {
        // wx.hideLoading();
        if (_res.data.error_code == 0) {
          var _split_ids = _res.data.data.split_ids;
          if (_split_ids.length) {
            for (let i = 0; i < _testInfo.length; i++) {
              if (paper_page == parseInt(_testInfo[i].page)) {
                _testInfo[i].split_ids = _split_ids;
              }
            }
            _this.setData({
              testInfo: _testInfo
            })
            _this.getTestImg(1);
          }
        }
      }
    })
  },

  /**
   * 点击拍照图标
   */
  photograph: function(e) {
    var _this = this,
      _index = e.currentTarget.dataset.index,
      _testInfo = _this.data.testInfo,
      _download_task_id = _this.data.codeInfo.download_task_id;
    var photoNum = wx.getStorageSync('photoNum');
    if (photoNum) {
      wx.setStorageSync('photoNum', photoNum + 1);
      if (photoNum <= 3) {
        _this.setData({
          'photoTip.photoTip': true,
          'curIndex': _index
        })
      } else {
        _this.setData({
          'photoTip.photoTip': false,
          'photoTip.current': 0,
          'curIndex': _index
        })
        _this.takePhoto();
      }
    } else {
      wx.setStorageSync('photoNum', 1);
      _this.setData({
        'photoTip.photoTip': true,
        'curIndex': _index
      })
    }
  },

  /**
   * 获取AI拍题图片上传完成后,图片列表 
   */
  getTestImg: function (status) {
    var _this = this,
    _testInfo = _this.data.testInfo;
    if (_this.data.isCallGetAiImg || _this.data.isTakingPhoto){
      return;
    }
    _this.setData({
      isCallGetAiImg: true
    })
    wx.showLoading({
      title: 'loading...',
      mask: true
    })
    if (_this.data.codeInfo.download_task_id) {
      var _download_task_id = 'download_task_id=' + _this.data.codeInfo.download_task_id;
    } else {
      var _download_task_id = "task_id=" + _this.data.codeInfo.paper_download_task_id;
    }
    if (_this.data.paper_id) {
      var paper_id = '&paper_id=' + _this.data.paper_id;
    } else {
      var paper_id = '';
    }
    console.warn(new Date(), 'testImg getTestImg - token', wx.getStorageSync('token'));
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/paperUploadStatus?' + _download_task_id + '&' + app.globalData.URLBOOL + paper_id,
      method: 'GET',
      success: function(res) {
        if (_this.data.firstEnter) {
          _this.setData({
            firstEnter: false 
          })
          wx.hideLoading();
        }
        else if(!_this.data.isCallCheckPageStatusNew && !_this.data.isTakingPhoto){//上传后不能隐藏-通过验证图片隐藏
          wx.hideLoading();
        }
        var _res = res.data;
        var paper_ids = [];
        var testimg = [];
        if (_res.error_code == 0) {
          for (var i = 0; i < _res.data.length; i++) {
            _res.data[i].url = "/pages/shootTopic/shootTopic?task_id=" + _res.task_id + "&paper_download_task_id=" + _res.data[i].paper_download_task_id + "&download_task_id=" + _download_task_id + "&paper_page=" + _res.data[i].paper_page + "&page=" + _res.data[i].page;
            if (_res.data[i].status == 1) {
              paper_ids.push(_res.data[i].paper_id);
            }
            if (status == 0) {
              _res.data[i].split_ids = [];
            } else if (status == 1) {
              _res.data[i].split_ids = _testInfo[i].split_ids;
            }
            testimg.push(_res.data[i].old_paper_img_url);
          }
          _this.setData({
            'testInfo': _res.data,
            'testImg': testimg,
            'task_id': _res.task_id,
            'kmapping_id': _res.kmapping_id,
            'paper_ids': paper_ids.join(",")
          })
        } else {
          wx.showToast({
            title: _res.error_msg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      complete: function(){
        _this.setData({
          isCallGetAiImg: false
        })
      }
    })
  },

  //授权登录并向后台发送 res.code 换取 openId, sessionKey, unionId
  login: function(obj = this) {
    var _this = this,
      code = null;
    wx.showLoading({
      title: 'loading...'
    })
    //配置域名地址信息
    wx.request({
      url: app.globalData.firstURL + '/kmapping/WeixinAppAjax/getConfig?lgc=1',
      method: 'GET',
      success: function(res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          for (var key in _res.data) {
            app.globalData[key] = _res.data[key];
          }
          // 登录
          wx.login({
            success: res => {
              code = res.code;
              var checkToken = wx.getStorageSync('token');
              if (checkToken) {
                console.warn(new Date(), 'testImg login - token', wx.getStorageSync('token'));
                wx.request({
                  url: app.globalData.URL + '/index.php?app=interface&mod=User&act=checkToken&token=' + checkToken,
                  method: 'GET',
                  success: function (_res) {
                    var res = _res.data;
                    if (res.error_code == 0) {
                      var data = res.data;
                      if (data.token_status == 0) {
                        if (data.expire_time >= app.globalData.expirationTime) {
                          var hxUserIds = app.globalData.huanxin_msg_user_ids,
                            userId = wx.getStorageSync('userId');
                          for (let i = 0; i < hxUserIds.length; i++) {
                            if (hxUserIds[i] == userId) {
                              app.globalData.hxConfigStatus = true
                            }
                          }
                          app.setUrlBool();
                          wx.hideLoading();
                          _this.judgeBind();
                        } else {
                          _this.weixinAppLogin(code);
                        }
                      } else {
                        _this.weixinAppLogin(code);
                      }
                    }
                  }
                })
              } else {
                _this.weixinAppLogin(code);
              }
            }
          })
        }
      }
    })
  },

  /**
     * 登陆接口
     */
  weixinAppLogin: function (code) {
    var _this = this;
        wx.request({
      url: app.globalData.URL + '/interface/WeixinApp/login?lgc=1&channel_no=' + wx.getStorageSync('channel_no'),
      data: {
        'code': code,
        'app_name': 'xiaochengxu_eknowme',
        'openid': wx.getStorageSync('openid'),
      },
      method: 'GET',
      success: function (_res) {
        if (_res.data.error_code == 0) {
          console.warn(new Date(), 'testImg weixinAppLogin - token', wx.getStorageSync('token'));
          var hxUser = _res.data.data.user_info.node_id + '_' + _res.data.data.user_info.uid;
          wx.setStorageSync('token', _res.data.data.token);
          wx.setStorageSync('openid', _res.data.data.openid);
          wx.setStorageSync('bindAcountBool', _res.data.data.bind_acount_bool);
          wx.setStorageSync('userId', _res.data.data.user_info.uid);
          wx.setStorageSync('myUsername', hxUser);
          var hxUserIds = app.globalData.huanxin_msg_user_ids
          for (let i = 0; i < hxUserIds.length; i++) {
            if (hxUserIds[i] == _res.data.data.user_info.uid) {
              app.globalData.hxConfigStatus = true
            }
          }
          app.setUrlBool();
          wx.hideLoading();
          _this.judgeBind();
        } else {
          _this.rebind();
        }
      }
    })
  },

  /**
   *登录失败重新绑定用户 
   */
  rebind: function() {
    var _this = this;
    var paramStr = '';
    var open_id = wx.getStorageSync('openid');
    if (!open_id) {
      wx.login({
        success: res => {
          paramStr = 'code=' + res.code;
          _this.noBindAcount(paramStr);
        }
      })
    } else {
      paramStr = 'open_id=' + open_id;
      _this.noBindAcount(paramStr);
    }
  },

  /**
   * 解绑请求
   */
  noBindAcount: function(paramStr) {
    var _this = this;
    wx.request({
      url: app.globalData.URL + '/interface/WeixinApp/noBindAcount?app_name=xiaochengxu_eknowme&lgc=1&' + paramStr,
      method: 'GET',
      success: function(_res) {
        wx.setStorageSync('bindAcountBool', false);
        _this.login(_this);
      }
    })
  },

  /**
   * 判断用户账号是否已绑定
   */
  judgeBind: function() {
    var _this = this;
    var bind_acount_bool = wx.getStorageSync('bindAcountBool');
    var code = this.data.code; console.warn(new Date(), 'testImg weixinAppLogin - user_id', wx.getStorageSync('user_id'));
    //如果未绑定，则可选择账号登录
    if (bind_acount_bool == false) {
      var codeInfo = JSON.stringify(_this.data.codeInfo);
      wx.reLaunch({
        url: "/pages/bind/bind?code=" + escape(codeInfo)
      });
    } else {
      var user_id = wx.getStorageSync('userId'),
        download_task_id = _this.data.codeInfo.download_task_id,
        paper_download_task_id = _this.data.codeInfo.paper_download_task_id;
      app.hxlogin();
      wx.request({
        url: app.globalData.URL + '/kmapping/WebAppAjax/checkPageStatus?' + app.globalData.URLBOOL,
        method: 'GET',
        data: {
          download_task_id: download_task_id,
          paper_download_task_id: paper_download_task_id,
          user_id: user_id,
          wechat_flag: 1
        },
        success: function (_res) {
          var res = _res.data;
          if (res.error_code == 0) {
            _this.getTestImg(0);
          } else {
            wx.showModal({
              title: '提示',
              content: res.error_msg,
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                }
              }
            })
          }
        }
      })
    }
  },

  /**
   * 答题卡跳转
   */
  answerCard: function() {
    var _this = this,
      task_id = this.data.task_id,
      paper_ids = this.data.paper_ids,
      kmapping_id = this.data.kmapping_id,
      _testInfo = _this.data.testInfo,
      _online = _this.data.online;
    if (_online == 1) {
      wx.navigateBack({
        delta: 1
      })
    } else {
      if (paper_ids == '' && _testInfo.length != 0){
        var paper_id_arr = [];
        for (let i = 0; i < _testInfo.length; i ++){
          paper_id_arr.push(_testInfo[i].paper_id);
        }
        paper_ids = paper_id_arr.join(',');
      }
      wx.navigateTo({
        url: '/pages/answerCard/answerCard?task_id=' + task_id + '&paper_ids=' + paper_ids + '&kmapping_id=' + kmapping_id
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    if (options.scene) {
      var _codeInfo = null,
          scene = null;
      if (options.scene.includes('app_id')) {
        _codeInfo = JSON.parse(unescape(options.scene));
      }
      else { 
        scene = decodeURIComponent(options.scene).replace(/'/g, "");
        var _result = scene.split("+");
        _codeInfo = {
          app_id: _result[0],
          paper_download_task_id: _result[1],
          page: _result[2],
          download_task_id: _result[3]
        };
      }
      _this.setData({
        codeInfo: _codeInfo,
        code: scene
      })
      console.warn(new Date(),'testImg onload - token',wx.getStorageSync('token'));
      _this.login(_this);
    }
    if (options.online == 1) {
      var _codeInfo = {
        app_id: 1101,
        paper_download_task_id: options.paper_download_task_id
      };
      _this.setData({
        online: 1,
        codeInfo: _codeInfo,
        paper_id: options.paper_id
      })
      _this.getTestImg(0);
    } else if (options.online == 0) {
      var _codeInfo = {
        app_id: options.app_id,
        paper_download_task_id: options.paper_download_task_id,
        page: options.page,
        download_task_id: options.download_task_id
      };
      _this.setData({
        online: 0,
        codeInfo: _codeInfo
      })
      _this.getTestImg(0);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this,
      _testInfo = _this.data.testInfo;
    if (!_this.data.isUploadingImg) {
      _this.getTestImg(0);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var _this = this,
      _testInfo = _this.data.testInfo,
      _online = _this.data.online;
    if (_online == 1) {
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];
      for (var i = 0; i < _testInfo.length; i++) {
        if (_testInfo[i].split_ids.length) {
          prevPage.setData({
            hxStatus: true
            //testInfo: _testInfo
          });
          break;
        }
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})